package net.qiqbframework.persisthanding;

import net.qiqbframework.loadhanding.JdbcAggregate;
import net.qiqbframework.messaging.GenericMessage;
import net.qiqbframework.messaging.MessageDecorator;
import net.qiqbframework.modelling.domain.Aggregate;

import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;


public class GenericPersistMessage<A> extends MessageDecorator<A> implements PersistMessage<A> {

    private final Aggregate<A> aggregate;

    private PersistMessage<A> next;


    public GenericPersistMessage(@Nonnull Aggregate<A> aggregate, @Nonnull Map<String, ?> metaData) {
        super(new GenericMessage<>(aggregate.aggregateRoot(), metaData));
        this.aggregate = aggregate;
    }

    public GenericPersistMessage(@Nonnull Aggregate<A> aggregate) {
        super(new GenericMessage<>(aggregate.aggregateRoot(), new HashMap<>()));
        this.aggregate = aggregate;
    }


    @Override
    protected String describeType() {
        return "GenericPersistMessage";
    }


    @Override
    public String getPersistName() {
        return aggregate.aggregateRootId().getModel().entityModel().modelName();
    }

    @Override
    public A getSnapshotAggregateRoot() {
        if (aggregate instanceof JdbcAggregate<A> jdbcAggregate) {
            return jdbcAggregate.getSnapshotAggregateRoot();
        }
        return null;
    }

    @Override
    public boolean isDeleted() {
        return aggregate.isDeleted();
    }

    @Override
    public boolean isNew() {
        return aggregate.isNew();
    }

    @Override
    public PersistMessage<A> next() {
        return this.next;
    }

    @Override
    public void next(PersistMessage<A> nextPersist) {
        this.next = nextPersist;
    }

}
